package com.wfs.ajax;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.fasterxml.jackson.databind.ObjectMapper;

import com.wfs.ajax.json.QRCodeJO;
import com.wfs.util.QRCodeGeneratorUtil;

public class QRCodeController extends HttpServlet {
	
	ObjectMapper mapper = new ObjectMapper();
	
	/**
	 * AJAX QRCode generator servlet, returns JSON serialized QRCodeJO 
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		try {
			MessageDigest m = MessageDigest.getInstance("MD5");
			StringBuilder sb = new StringBuilder();
			sb.append(System.nanoTime());
			String randomString = sb.toString();
			m.update(randomString.getBytes(), 0, randomString.length());
			String gen_token = new BigInteger(1,m.digest()).toString(16);
			
			QRCodeJO qr = new QRCodeJO(QRCodeGeneratorUtil.generateQRFromText(gen_token),gen_token);
			resp.getWriter().write(mapper.writeValueAsString(qr));
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			// handle generic error
		}
	}
	

}
